<template>
	<view class="knowledge">
		<view v-if="!searchLoading">
			<view v-if="productList && productList.length > 0">
				<scroll-view @scrolltolower="nextPage" @refresherrefresh="refresh" refresher-enabled :refresher-triggered="isRefreshing" scroll-y
					:style="{height: 'calc(100vh - ' + safeAreaInsetBottom + 'px)'}">
					<view class="product-list">
						<view
						  v-for="(item, index) in productList" 
						  :key="item.id" 
						  class="product-item"
						>
							<view style="width: calc(100vw - 80rpx);">
								<view @click="goDetail(item.id)" class="flex">
									<view class="product-image">
									  <u-image 
										:src="item.imgUrl" 
										width="120rpx" 
										height="120rpx" 
										mode="aspectFill"
									  ></u-image>
									</view>
									<view class="product-info">
									  <view class="product-name">{{ item.name }}</view>
									  <view class="product-desc" v-html="item.description"></view>
									</view>
								</view>
								<view class="flex justify-end">
									<view class="product-actions">
										<view class="mr-10">
											<u-button
												size="mini" 
												type="primary" 
												plain
												@click.stop="editProduct(item.id)"
											>编辑</u-button>
										</view>
									  <view>
										  <u-button
												size="mini" 
												type="error" 
												plain
												@click.stop="confirmDelete(item.id, index)"
										  >删除</u-button>
									  </view>
									  
									</view>
								</view>
								
							</view>
						  
						  
						</view>
					</view>
					<u-loadmore :status="loadMoreStatus" />
				</scroll-view>
			</view>
			<view v-else class="flex align-center justify-center"
				:style="{height: 'calc(100vh - ' + safeAreaInsetBottom + 'rpx)'}">
				<u-empty mode="search"></u-empty>
			</view>
		</view>
		<view v-else class="pt-20">
			<u-skeleton rows="30" :title="false" :loading="searchLoading"></u-skeleton>
		</view>
		<!-- 添加产品悬浮按钮 -->
		<view class="add-btn">
		  <u-button 
		    type="primary" 
		    shape="circle" 
		    icon="plus" 
		    @click="addProduct"
		  ></u-button>
		</view>
		
		<!-- 删除确认弹窗 -->
		<u-modal 
		  :show="showDeleteModal" 
		  :content="deleteContent" 
		  :show-cancel-button="true"
		  @cancel="showDeleteModal=false"
		  @confirm="deleteProduct"
		></u-modal>
		<u-toast ref="toast"></u-toast>
	</view>
</template>

<script>
	import api from "@/api/api";
	export default {
		data() {
			return {
				safeAreaInsetBottom: 0,
				productList: [],
				page: 0,
				size: 10,
				errorMsgVisible: false,
				errorMsg: "",
				searchLoading: true,
				loadMoreStatus: "loadmore",
				apiKey: null,
				knowledgeBase: null,
				modalVisible: false,
				selectedFile: null,
				selectedFileIndex: null,
				isRefreshing: false,
				showDeleteModal: false, // 是否显示删除弹窗
				deleteContent: '确定要删除该产品吗？', // 删除弹窗内容
				deletingId: null, // 正在删除的产品ID
				deletingIndex: null // 正在删除的产品索引
			}
		},
		async onLoad() {
			let safeAreaInsets = uni.getSystemInfoSync().safeAreaInsets;
			this.safeAreaInsetBottom = safeAreaInsets.bottom;
			this.loadProductList();
			uni.$on('editProductSuccess', (product) => {
				if (product && product.id) {
					let productInList = this.productList.find(item => item.id === product.id)
					if (productInList) {
						Object.assign(productInList, product)
					}
				}
			})
			uni.$on('createProductSuccess', (product) => {
				this.productList = [product, ...this.productList]
			})
			
		},
		onShow() {},
		methods: {
			async loadKnowledgeBase() {
				let knowledgeBase = await this.depot.get(api.aiCard(
					"product/findByChatAssistantTypeAndType?chatAssistantType=AI_CARD&type=DEFAULT"
					))
				knowledgeBase = knowledgeBase && knowledgeBase.data && knowledgeBase.data.data ? knowledgeBase.data
					.data : null;
				this.knowledgeBase = knowledgeBase;
				this.apiKey = knowledgeBase && knowledgeBase.ragflowUser ? knowledgeBase.ragflowUser.apiKey : null;
			},
			loadProductList() {
				let url = "product/findProductPage?page=" +
					this.page + "&size=" + this.size;
				this.depot.post(api.aiCard(url), null).
				then(response => {
					this.isRefreshing = false
					this.$nextTick(() => { this.isRefreshing = false })
					if (response && response.data && response.data.data) {
						if (response.data.data.content && response.data.data.content.length) {
							if (response.data.data.content.length < this.size) {
								this.loadMoreStatus = "nomore"
							} else {
								this.loadMoreStatus = "loadmore"
							}
						} else {
							this.loadMoreStatus = "nomore"
						}
						this.productList = this.productList.concat(response.data.data.content);
					}
				}).finally(() => {
					this.searchLoading = false;
				})
			},
			nextPage() {
				this.page++;
				this.loadMoreStatus = "loading";
				this.loadProductList();
			},
			refresh() {
				this.page = 0;
				this.productList = [];
				this.loadMoreStatus = "loading";
				this.loadProductList();
			},
			companyInfoClick(companyInfo) {
				if (companyInfo && companyInfo.companyInfoId) {
					uni.navigateTo({
						url: "/pages/companySearch/companyInfo?companyInfoId=" + companyInfo.companyInfoId
					})
				}
			},
			// 上传文件
			uploadFile() {
				let knowledgeBaseId = this.knowledgeBase.knowledgeBaseId;
				if (!knowledgeBaseId || !this.apiKey) {
					console.log("知识库信息未加载");
					return;
				}
				uni.chooseMessageFile({
					count: 1,
					type: 'all',
					success: async (res) => {
						const tempFile = res.tempFiles[0];
						console.log(tempFile.name)
						this.$u.toast('文件上传中...');

						try {
							//上传
							let header = {
								Authorization: "Bearer " + this.apiKey
							}
							const uploadRes = await this.depot.uploadFile(api.ragflow("datasets/" +
								knowledgeBaseId + "/documents"), tempFile.path, header);
							let documentInfo = uploadRes && uploadRes.data && uploadRes.data.length ? uploadRes
								.data[0] : null;
							if (documentInfo && documentInfo.id) {
								// 文件名称是随机字符串， 需要更新文件名称
								await this.depot.put(api.ragflow("datasets/" + knowledgeBaseId +
									"/documents/" + documentInfo.id), {
									"name": tempFile.name
								}, header)
								documentInfo.name = tempFile.name;
								// 添加到列表顶部
								this.productList.unshift(documentInfo);
								//TODO 启动文件解析并且绑定知识库到聊天助手
								//开始文件解析
								let documentIds = [documentInfo.id];
								await this.depot.post(api.ragflow("datasets/" + knowledgeBaseId +
									"/chunks"), {
									"document_ids": documentIds
								}, header)
							}
							this.$u.toast('上传成功');
						} catch (e) {
							console.error(e);
							this.$u.toast('上传失败');
						}
					}
				});
			},
			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					DONE: '解析成功',
					UNSTART: '解析中',
					RUNNING: '解析中',
					error: '解析失败'
				};
				return statusMap[status] || '未知状态';
			},
			// 删除文件
			deleteFile(productInfo, index) {
				this.selectedFile = productInfo;
				this.selectedFileIndex = index;
				this.modalVisible = true;
			},
			async delConfirmBtnClick() {
				this.modalVisible = false;
				let id = this.selectedFile && this.selectedFile.id ? this.selectedFile.id : null;
				if (!id) {
					return;
				}
				let header = {
					Authorization: "Bearer " + this.apiKey
				}
				await this.depot.delete(api.ragflow("datasets/" + this.knowledgeBase.knowledgeBaseId +
					"/documents"), {
					"ids": [id]
				}, header)
				this.productList.splice(this.selectedFileIndex, 1)
					
				this.$refs.toast.show({
					type: "success",
					title: "提示",
					message: "文件删除成功"
				});
				
			},
			editProduct(id) {
				uni.navigateTo({
				  url: '/pages/product/edit?id=' + id
				})
			},
			// 添加产品
			addProduct() {
			  uni.navigateTo({
			    url: '/pages/product/edit'
			  })
			},
			// 确认删除
			confirmDelete(id, index) {
			  this.deletingId = id
			  this.deletingIndex = index
			  this.showDeleteModal = true
			},
			
			// 删除产品
			async deleteProduct() {
			  try {
			    // 这里替换为你的实际API请求
			    await this.depot.get(api.aiCard("product/deleteProductById?id=" + this.deletingId), null);
			    
			    // 从列表中移除
			    this.productList.splice(this.deletingIndex, 1)
			    this.total--
			    
			    this.$u.toast('删除成功')
				this.showDeleteModal = false;
			  } catch (error) {
			    console.error(error)
			    this.$u.toast('删除失败')
			  } finally {
			    this.deletingId = null
			    this.deletingIndex = null
			  }
			},
			goDetail(id) {
				uni.navigateTo({
				  url: '/pages/product/detail?id=' + id
				})
			},
			formatDate(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');

				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			}
		}
	}
</script>

<style lang="less" scoped>
	.knowledge {
		min-height: 100vh;
		background-color: #fff;

		&-top {
			height: 476rpx;
			background: url(https://biz-miniapp.oss-cn-beijing.aliyuncs.com/newVersionImg/topBgc.png) no-repeat;
			background-size: 100% 100%;
			position: relative;

			&-sty {
				height: 88rpx;
			}

			&-title {
				position: fixed;
				left: 0;
				width: 100%;
				padding: 0 30rpx;
				line-height: 80rpx;
				color: #fff;
				z-index: 20;

				text {
					display: inline-block;
					width: 30rpx;
				}

				view {
					font-weight: bold;
				}
			}

			&-search {
				line-height: 68rpx;
				border-radius: 34rpx;
				border-color: #333;
				padding: 0rpx 16rpx;
				margin: 0rpx 10rpx;

				input {
					color: #666;
					flex: 1;
					margin: 15rpx 20rpx;
				}

				&-pla {
					color: #999;
				}

				button {
					width: 100rpx;
					line-height: 50rpx;
					background: linear-gradient(153deg, #5c8df7 0%, #2f54eb 100%);
					border-radius: 25rpx;
					color: #fff;
				}
			}
		}

		&-history {
			padding-left: 20rpx;
			margin-top: 20rpx;

			&-title {
				font-size: 28rpx;
				color: #fff;
			}

			/deep/.u-tag--primary--plain {
				border-color: #fff;
			}

			/deep/.u-tag__text--primary--plain {
				color: #fff;
			}
		}

		&-total {
			padding: 20rpx;
			color: #333;
			background-color: #fff;
			border-bottom: 1rpx solid #e6e6e6;
		}

		&-list {
			padding: 25rpx;
			border-bottom: 1rpx solid #e6e6e6;

			&-title {
				button {
					width: 100rpx;
					line-height: 50rpx;
					background: rgba(26, 108, 255, 0.1);
					border-radius: 25rpx;
					color: #2f54eb;
					font-weight: bold;
				}

				&-name {
					color: #333;
				}
			}

			&-label {
				color: #999;

				>text {
					display: inline-block;
					padding: 0 20rpx;
					border-right: 1rpx solid #e6e6e6;

					&:last-child {
						border-right: 0;
					}

					&:first-child {
						padding-left: 0;
					}
				}
			}

			&-tel {
				color: #666;
			}

			&-user {
				color: #666;
			}
		}
	}

	.product-list {
	  padding: 20rpx 20rpx 0rpx 20rpx;
	  
	  .product-item {
	    display: flex;
	    padding: 20rpx;
		width: calc(100vw - 40rpx);
	    margin-bottom: 20rpx;
	    background-color: #fff;
	    border-radius: 10rpx;
	    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	    
	    .product-image {
	      margin-right: 20rpx;
	    }
	    
	    .product-info {
	      flex: 1;
	      
	      .product-name {
	        font-size: 30rpx;
	        font-weight: bold;
	        margin-bottom: 10rpx;
	        color: #333;
	      }
	      
	      .product-desc {
	        font-size: 26rpx;
	        color: #999;
	        overflow: hidden;
	        text-overflow: ellipsis;
	        display: -webkit-box;
	        -webkit-line-clamp: 2;
	        -webkit-box-orient: vertical;
	      }
	    }
	    
	    .product-actions {
	      display: flex;
		  justify-content: space-between;
		  margin-top: 20rpx;
		  width: 200rpx;
	      .u-button {
	        margin: 5rpx;
	        width: 100rpx;
	      }
	    }
	  }
	}

	.upload-btn-container {
		padding: 20rpx;
		background-color: #fff;
		box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);

		/deep/ .u-btn {
			height: 80rpx;
		}
	}

	.safe-area-inset-bottom {
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}
	
	.add-btn {
	  position: fixed;
	  right: 40rpx;
	  bottom: 80rpx;
	  
	  .u-button {
	    width: 100rpx;
	    height: 100rpx;
	  }
	}
</style>